package com.sec.security;

import java.util.*;

import com.sec.dao.mysql.view.UserViewDao;
import com.sec.domain.mysql.view.UserView;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;

import com.sec.util.impl.AntUrlPathMatcher;
import com.sec.util.UrlMatcher;

import javax.annotation.Resource;

/**
 * loadResourceDefine方法不是必须的，这个只是加载所有的资源与权限的对应关系并缓存起来，避免每次获取权限都访问数据库（提高性能），然后getAttributes根据参数（被拦截url）返回权限集合。
 * Created by Administrator on 2017/10/31.
 */
public class MyInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private UrlMatcher urlMatcher = new AntUrlPathMatcher();
    private static Map<String, Collection<ConfigAttribute>> resourceMap = null;

    @Resource
    private UserViewDao userViewDao;

    //tomcat启动时实例化一次
    public MyInvocationSecurityMetadataSource() {
        //loadResourceDefine();
    }
    //tomcat开启时加载一次，加载所有url和权限（或角色）的对应关系
    private void loadResourceDefine() {
        /*if(resourceMap == null){
            resourceMap = new HashMap<>();

            List<UserPerm> userPermList = userPermDao.queryAll();
            Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
            for(UserPerm userPerm : userPermList){
                Role role = roleDao.queryById(userPerm.getRole_id());
                com.sec.domain.mysql.Resource resource = resourceDao.queryById(userPerm.getResource_id());
                ConfigAttribute ca = new SecurityConfig(role.getRole_name());
                atts.add(ca);
                resourceMap.put(resource.getUrl(), atts);
            }

            Collection<ConfigAttribute> atts = new ArrayList<ConfigAttribute>();
            ConfigAttribute ca = new SecurityConfig("ROLE_USER");
            atts.add(ca);
            resourceMap.put("/index.jsp", atts);
            Collection<ConfigAttribute> attsno =new ArrayList<ConfigAttribute>();
            ConfigAttribute cano = new SecurityConfig("ROLE_NO");
            attsno.add(cano);
            resourceMap.put("/other.jsp", attsno);
            Collection<ConfigAttribute> attsadmin =new ArrayList<ConfigAttribute>();
            ConfigAttribute canoadmin = new SecurityConfig("ROLE_ADMIN");
            attsadmin.add(canoadmin);
            resourceMap.put("/admin.jsp", attsadmin);
        }*/
    }

    //参数是要访问的url，返回这个url对于的所有权限（或角色）
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        String url = ((FilterInvocation)object).getRequestUrl();
        UserView userView = new UserView();
        userView.setUrl(url);
        //List<UserView> userViewList = userViewDao.queryByCon(userView);
        userViewDao.queryByCon(userView);
        List<UserView> userViewList =  new ArrayList<>();
        Collection<ConfigAttribute> atts = new ArrayList<>();
        if(userViewList!=null && userViewList.size()>0){
            for(UserView userView1 : userViewList){
                ConfigAttribute configAttribute = new SecurityConfig(userView1.getRoleName());
                atts.add(configAttribute);
            }
        }
        return atts;
       /* // 将参数转为url
        String url = ((FilterInvocation)object).getRequestUrl();
        Iterator<String>ite = resourceMap.keySet().iterator();
        while (ite.hasNext()) {
            String resURL = ite.next();
            if (urlMatcher.pathMatchesUrl(resURL, url)) {
                return resourceMap.get(resURL);
            }
        }
        return null;*/
    }
    public boolean supports(Class<?>clazz) {
        return true;
    }
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }
}
